<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="套餐名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入套餐名" />
      </el-form-item>
      <el-form-item label="菜单权限" prop="menuIds">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuCheckAll" @change="handleCheckedTreeCheckAll"
        >全选/全不选</el-checkbox
        >
        <el-checkbox v-model="menuCheckLinked">父子联动</el-checkbox>
        <el-tree
          ref="menuTreeRef"
          class="tree-border h-400px overflow-auto"
          :data="menuTree"
          :props="defaultProps"
          empty-text="加载中，请稍候"
          node-key="id"
          show-checkbox
          :check-strictly="!menuCheckLinked"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in common_enable_status"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
      <template #footer>
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
  </Dialog>
</template>

<script setup lang="ts">
import { TenantPackageApi, TenantPackageVO } from '@/api/system/tenant/tenant_package'
import * as MenuApi from '@/api/system/menu'
import { FormRules } from 'element-plus'
import {EnableStatusEnum} from "@/utils/constants";
import {defaultProps, handleTree} from "@/utils/tree";

defineOptions({ name: 'SystemTenantPackageForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { common_enable_status } = useIntDict( DICT_TYPE.common_enable_status )

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formDataObj = {
  id: undefined,
  name: undefined,
  menuIds: [] as any[],
  remark: undefined,
  status: EnableStatusEnum.Enabled
}
const formData = ref({ ...formDataObj })
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '套餐名不能为空', trigger: 'blur' }],
  menuIds: [{ required: true, message: '菜单权限不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const menuTree = ref() // 菜单树数据
const menuExpand = ref(false) // 是否展开
const menuCheckAll = ref(false) // 全选/全不选
const menuCheckLinked = ref(true) // 是否父子联动
const menuTreeRef = ref() // 菜单树组件

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  menuTree.value = handleTree(await MenuApi.getMenuSimpleList(EnableStatusEnum.Enabled))
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantPackageApi.getTenantPackage(id)
      nextTick(() => {
        formData.value.menuIds.forEach((menuId) => {
          menuTreeRef.value.setChecked(menuId, true, false)
        })
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  formData.value.menuIds = [
    ...menuTreeRef.value.getCheckedKeys(false), // 获取到选中节点的keys(leafOnly: false， 不仅仅只包括leaf节点)
    ...menuTreeRef.value.getHalfCheckedKeys() // 获取半选中节点的keys(即其所有子节点未全部选中的节点)
  ]
  if (await formValidate(formRef)) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantPackageVO
    if (formType.value === 'create') {
      await TenantPackageApi.createTenantPackage(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantPackageApi.updateTenantPackage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...formDataObj }
  formRef.value?.resetFields()
  menuExpand.value = false
  menuCheckAll.value = false
  menuCheckLinked.value = true
  menuTreeRef.value?.setCheckedNodes([])
}

const handleCheckedTreeExpand = () => {
  const nodes = menuTreeRef.value?.store.nodesMap
  for (const nodeKey in nodes) {
    if (nodes[nodeKey].expanded !== menuExpand.value) {
      nodes[nodeKey].expanded = menuExpand.value
    }
  }
}

const handleCheckedTreeCheckAll = () => {
  menuTreeRef.value?.setCheckedNodes(menuCheckAll.value ? menuTree.value : [])
}
</script>

<style scoped lang="scss"></style>
